package com.dfy.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dfy.common.Result;
import com.dfy.dto.OrderRequest;
import com.dfy.dto.OrderResponse;
import com.dfy.dto.OrderListRequest;
import com.dfy.dto.TripDTO;
import com.dfy.entity.Order;
import com.dfy.service.OrderService;
import com.dfy.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.context.SecurityContextHolder;
import javax.servlet.http.HttpServletRequest;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.security.core.Authentication;

@Slf4j
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    // 创建订单
    @PostMapping
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public Result<OrderResponse> createOrder(
            @Validated @RequestBody OrderRequest request,
            HttpServletRequest servletRequest) {
        log.info("创建订单请求，原始数据: {}", request);
        log.info("spotId: {}", request.getSpotId());
        log.info("visitDate: {}", request.getVisitDate());
        log.info("quantity: {}", request.getQuantity());
        log.info("contactName: {}", request.getContactName());
        log.info("contactPhone: {}", request.getContactPhone());
        log.info("remark: {}", request.getRemark());
        log.info("请求头信息: Content-Type={}", servletRequest.getContentType());
        
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        log.info("当前用户: {}, 角色: {}", auth.getName(), auth.getAuthorities());
        
        String userId = auth.getName();
        Order order = orderService.createOrder(request.getSpotId(), Long.parseLong(userId), request);
        return Result.success(orderService.getOrder(order.getId()));
    }

    // 获取订单详情
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('USER')")
    public Result<OrderResponse> getOrder(@PathVariable String id) {
        try {
            Long orderId = Long.parseLong(id);
            log.info("获取订单详情，ID：{}", orderId);
            String userId = SecurityContextHolder.getContext().getAuthentication().getName();
            OrderResponse response = orderService.getOrder(orderId);
            
            // 验证订单所属权
            if (!response.getUserId().equals(Long.parseLong(userId))) {
                throw new BusinessException(403, "无权查看订单");
            }
            
            return Result.success(response);
        } catch (NumberFormatException e) {
            throw new BusinessException(400, "无效的订单ID");
        }
    }

    // 取消订单
    @PostMapping("/{id}/cancel")
    @PreAuthorize("hasRole('USER')")
    public Result<?> cancelOrder(@PathVariable String id) {
        try {
            Long orderId = Long.parseLong(id);
            log.info("取消订单请求，订单ID：{}", orderId);
            String userId = SecurityContextHolder.getContext().getAuthentication().getName();
            orderService.cancelOrder(orderId, Long.parseLong(userId));
            return Result.success("订单已取消");
        } catch (NumberFormatException e) {
            throw new BusinessException(400, "无效的订单ID");
        }
    }

    // 获取我的订单列表
    @GetMapping("/my")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public Result<Page<OrderResponse>> getMyOrders(
            @RequestParam(required = false, defaultValue = "ALL") String status,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        log.info("获取我的订单列表，状态：{}，页码：{}，每页数量：{}", status, current, size);
        
        // 获取当前用户ID
        String userId = SecurityContextHolder.getContext().getAuthentication().getName();
        log.debug("Current userId: {}", userId);
        
        // 继续使用原来的方法，不改变现有逻辑
        OrderListRequest request = new OrderListRequest();
        request.setUserId(Long.valueOf(userId));
        request.setStatus("ALL".equals(status) ? null : status);
        request.setPageNum(current);
        request.setPageSize(size);
        
        return Result.success(orderService.getOrderPage(request));
    }

    // 获取我的行程列表
    @GetMapping("/trips")
    public Result<List<TripDTO>> getMyTrips(
        @RequestParam String startDate,
        @RequestParam String endDate
    ) {
        String userId = SecurityContextHolder.getContext().getAuthentication().getName();
        
        try {
            LocalDateTime startDateTime = startDate != null && !startDate.equals("undefined") ? 
                LocalDate.parse(startDate).atStartOfDay() : 
                LocalDate.now().atStartOfDay();
                
            LocalDateTime endDateTime = endDate != null && !endDate.equals("undefined") ? 
                LocalDate.parse(endDate).atTime(23, 59, 59) : 
                startDateTime.plusMonths(1).minusSeconds(1);
            
            log.info("获取用户{}的行程列表，开始日期：{}结束日期：{}", 
                    userId, startDateTime, endDateTime);
                    
            List<TripDTO> trips = orderService.getUserTrips(
                Long.parseLong(userId), 
                startDateTime,
                endDateTime
            );
            
            return Result.success(trips);
        } catch (Exception e) {
            log.error("获取行程列表失败：", e);
            throw new BusinessException(400, "日期格式错误，请使用 yyyy-MM-dd 格式");
        }
    }

    // 管理员获取所有订单列表
    @GetMapping("/admin/list")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Page<OrderResponse>> getAllOrders(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false, defaultValue = "1") Integer current,
            @RequestParam(required = false, defaultValue = "10") Integer size,
            @RequestParam(required = false) String sortField,
            @RequestParam(required = false, defaultValue = "desc") String sortOrder) {
            
        OrderListRequest request = new OrderListRequest();
        request.setStatus("undefined".equals(status) ? null : status);
        request.setKeyword("undefined".equals(keyword) ? null : keyword);
        request.setPageNum(current);
        request.setPageSize(size);
        request.setSortField("undefined".equals(sortField) ? null : sortField);
        request.setSortOrder(sortOrder);
        
        log.info("管理员获取订单列表，请求参数：{}", request);
        Page<OrderResponse> page = orderService.getOrderPage(request);
        return Result.success(page);
    }

    // 管理员确认订单
    @PostMapping("/admin/{id}/confirm")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> confirmOrder(@PathVariable String id) {
        try {
            Long orderId = Long.parseLong(id);
            log.info("管理员确认订单，订单ID：{}", orderId);
            orderService.confirmOrder(orderId);
            return Result.success("订单已确认");
        } catch (NumberFormatException e) {
            throw new BusinessException(400, "无效的订单ID");
        }
    }

    // 管理员取消订单
    @PostMapping("/admin/{id}/cancel")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> adminCancelOrder(
            @PathVariable String id,
            @RequestParam(required = false) String reason) {
        try {
            Long orderId = Long.parseLong(id);
            log.info("管理员取消订单，订单ID：{}，原因：{}", orderId, reason);
            orderService.adminCancelOrder(orderId, reason);
            return Result.success("订单已取消");
        } catch (NumberFormatException e) {
            throw new BusinessException(400, "无效的订单ID");
        }
    }

    // 管理员查看订单详情
    @GetMapping("/admin/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<OrderResponse> getOrderDetail(@PathVariable String id) {
        try {
            Long orderId = Long.parseLong(id);
            log.info("管理员查看订单详情，订单ID：{}", orderId);
            return Result.success(orderService.getOrder(orderId));
        } catch (NumberFormatException e) {
            throw new BusinessException(400, "无效的订单ID");
        }
    }
} 